package com.jpush.adapter;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.util.TraceClassVisitor;

import java.io.PrintWriter;

public class EnhancerAdapter extends ClassVisitor {

    private TraceClassVisitor tracer;

    public EnhancerAdapter(ClassVisitor cv) {
        super(Opcodes.ASM7,cv);
        PrintWriter pw = new PrintWriter(System.out);
        tracer = new TraceClassVisitor(cv,pw);
    }

    private boolean isAbstract(int access){
        return (Opcodes.ACC_ABSTRACT & access) == Opcodes.ACC_ABSTRACT;
    }

    private boolean isFinalMethod(int access){
        return (Opcodes.ACC_FINAL & access) == Opcodes.ACC_FINAL;
    }

    private boolean isIgnore(MethodVisitor mv,int access,String methodName){
        return mv == null
                || isAbstract(access)
                || isFinalMethod(access)
                || "<clinit>".equals(methodName)
                || "<init>".equals(methodName);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor mv = tracer.visitMethod(access, name, descriptor, signature, exceptions);
        if (isIgnore(mv,access,name)){
            return mv;
        }
        System.out.println("enhance name:"+name);
        System.out.println("enhance descriptor:"+descriptor);

        return new EnhancerMethodAdapter(mv,access,name,descriptor);
    }
}
